Random Number
Generate random numbers quickly.
The random!
Marco
use random;
let n: u8 = random!;
println!; // 0 ~ 255
let n: f64 = random!;
println!; // 0.0 ~ 1.0
let n: u8 = random!;
println!; // 0 ~ 10
let n: u8 = random!;
println!; // 0 ~ 9
let n: u8 = random!;
println!; // 10 ~ 255
let n: i8 = random!;
println!; // -2 ~ 12
let n: u8 = random!;
println!; // 12 ~ 20
let n: u8 = random!;
println!; // 12 ~ 20
The random number generator can be reused by adding it to the random!
macro as the last argument.
use random;
let mut rng = thread_rng;
let n: u8 = random!;
println!; // 0 ~ 255
let n: u8 = random!;
println!; // 0 ~ 10
let n: u8 = random!;
println!; // 12 ~ 20
The random_ranged
Function
If the range is not literal, for example, a variable, var_range
, storing an instance that implements the RangeBounds
trait, the var_range
variable cannot be used in the random!
macro.
let var_range = 1..=10;
let n: u8 = random!; // compile error
In this case, use the random_ranged
function instead.
let var_range = 1..=10;
let n: u8 = random_ranged;
println!; // 1 ~ 10
The random_fill!
Marco
The random_fill!
marco can be used to fill a slice with random numbers. The usage is like the random!
macro. Just add a slice as the first argument when using the random_fill!
macro.
let mut a = ;
random_fill!;
println!;
The random_fill_ranged
Function
let var_range = 1..=10;
let mut a = ;
random_fill_ranged;
println!;
Crates.io
https://crates.io/crates/random-number